package com.humanres.activity;

import android.graphics.Color;
import android.graphics.Typeface;
import android.util.Log;
import android.view.View;
import android.widget.GridView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ciko.code.base.BaseActicity;
import com.ciko.code.bean.MonthAttendsBean;
import com.ciko.code.http.BaseResponse;
import com.ciko.code.http.Req.GetMonthAttendsByUserEty;
import com.ciko.code.http.Req.GetMonthAttendsByUserReq;
import com.ciko.code.views.calendar.CalendarAdapter;
import com.ciko.code.views.calendar.SpecialCalendar;
import com.mywork.R;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

/**
 * Created by ciko on 2015/12/12.
 */
public class ResCheckActivity extends BaseActicity {

    //    private GestureDetector gestureDetector = null;
    private CalendarAdapter calendarAdapter = null;
    private GridView mGridView = null;
    private TextView topText = null;
    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
    private boolean isLeapyear = false;  //是否为闰年
    private int daysOfMonth = 0;      //某月的天数
    private int dayOfWeek = 0;        //具体某一天是星期几
    private int lastDaysOfMonth = 0;  //上一个月的总天数
    private int jumpMonth = 0; // 每次滑动，增加或减去一个月,默认为0（即显示当前月）
    private int jumpYear = 0; // 滑动跨越一年，则增加或者减去一年,默认为0(即当前年)
    private int mYear = 0;
    private int mMonth = 0;
    private int mDay = 0;
    private String currentDate = "";
    private String currentYear = "";
    private String currentMonth = "";
    private SpecialCalendar sc = null;
    private RelativeLayout nextMonth; // 下一月文本框
    private RelativeLayout preMonth; // 上一月文本框
    private RelativeLayout rl_rightview;
    private RelativeLayout rl_leftview;
    private String title = "";
    List<MonthAttendsBean> MonthAttendsBeanList = new ArrayList<>();
    List<GetMonthAttendsByUserEty> MonthAttendsByUserList = new ArrayList<>();

    @Override
    protected void initTopBar() {
        if (getIntent().getExtras().containsKey("title")) {
            title = getIntent().getStringExtra("title");
        }
        setTitle(title);
        enableNavLeftImg();

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M-d", Locale.CHINA);
        currentDate = sdf.format(date); // 当期日期
        mYear = Integer.parseInt(currentDate.split("-")[0]);
        mMonth = Integer.parseInt(currentDate.split("-")[1]);
        mDay = Integer.parseInt(currentDate.split("-")[2]);
        currentYear = mYear + "";
        //得到当前的年份
        currentMonth = mMonth + "";
    }

    @Override
    protected void initLayout() {

        setContentView(R.layout.activity_res_check);

        rl_leftview = (RelativeLayout) findViewById(R.id.left_img);
        rl_rightview = (RelativeLayout) findViewById(R.id.right_img);

        rl_leftview.setOnClickListener(this);
        rl_rightview.setOnClickListener(this);
    }

    @Override
    protected void initView() {
        sc = new SpecialCalendar();

        mGridView = (GridView) findViewById(R.id.gridview);
//        gestureDetector = new GestureDetector(this, new MyGestureListener());
        calendarAdapter = new CalendarAdapter(this, MonthAttendsBeanList);
//        addGridView();
        mGridView.setAdapter(calendarAdapter);

        topText = (TextView) findViewById(R.id.tv_month);
        addTextToTopTextView(topText);

        initCalender();

    }

    @Override
    protected void initAdapter() {

    }

    @Override
    protected void initDates() {
//        获取指定月所有的记录
        long time = new Date().getTime();
        Calendar cale = Calendar.getInstance();
        cale.set(Calendar.DATE, 3);
        doRequestHttp(new GetMonthAttendsByUserReq(cale.getTimeInMillis()));
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initHttpRequest() {

    }

    @Override
    public void onResponseSuccess(BaseResponse<?> response, String tag) {
        super.onResponseSuccess(response, tag);

        switch (tag) {
            case "GetMonthAttendsByUserReq":
                List<GetMonthAttendsByUserEty> getMonthAttendsByUserListResult = (List<GetMonthAttendsByUserEty>) response.getReturnObject();
                MonthAttendsByUserList.clear();
                MonthAttendsByUserList.addAll(getMonthAttendsByUserListResult);
                initCalender();
//                resListOverWorkAdapter.notifyDataSetChanged();
                break;

        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);

        if (v == rl_rightview) {
//                addGridView(); // 添加gridView
            jumpMonth++; // 下一个月

            int stepYear = mYear + jumpYear;
            int stepMonth = mMonth + jumpMonth;
            if (stepMonth > 0) {
                //往下一个月滑动
                if (stepMonth % 12 == 0) {
                    stepYear = mYear + stepMonth / 12 - 1;
                    stepMonth = 12;
                } else {
                    stepYear = mYear + stepMonth / 12;
                    stepMonth = stepMonth % 12;
                }
            } else {
                //往上一个月滑动
                stepYear = mYear - 1 + stepMonth / 12;
                stepMonth = stepMonth % 12 + 12;
                if (stepMonth % 12 == 0) {

                }
            }

            currentYear = String.valueOf(stepYear);
            //得到当前的年份
            currentMonth = String.valueOf(stepMonth);  //得到本月 （jumpMonth为滑动的次数，每滑动一次就增加一月或减一月）
            Calendar cale = Calendar.getInstance();
            cale.set(Calendar.YEAR, stepYear);
            cale.set(Calendar.MONTH, stepMonth - 1);
            cale.set(Calendar.DATE, 3);
            MonthAttendsByUserList.clear();
            initCalender();
            doRequestHttp(new GetMonthAttendsByUserReq(cale.getTimeInMillis()));
//                calendarAdapter = new CalendarAdapter(ResCheckActivity.this,
//                        getResources(), new Date(), jumpMonth, jumpYear,
//                        mYear, mMonth, mDay);
//                mGridView.setAdapter(calendarAdapter);
            addTextToTopTextView(topText);
        } else if (v == rl_leftview) {
//                addGridView(); // 添加gridView
            jumpMonth--; // 上一个月
            int stepYear2 = mYear + jumpYear;
            int stepMonth2 = mMonth + jumpMonth;
            if (stepMonth2 > 0) {
                //往下一个月滑动
                if (stepMonth2 % 12 == 0) {
                    stepYear2 = mYear + stepMonth2 / 12 - 1;
                    stepMonth2 = 12;
                } else {
                    stepYear2 = mYear + stepMonth2 / 12;
                    stepMonth2 = stepMonth2 % 12;
                }
            } else {
                //往上一个月滑动
                stepYear2 = mYear - 1 + stepMonth2 / 12;
                stepMonth2 = stepMonth2 % 12 + 12;
                if (stepMonth2 % 12 == 0) {

                }
            }

            currentYear = String.valueOf(stepYear2);
            //得到当前的年份
            currentMonth = String.valueOf(stepMonth2);  //得到本月 （jumpMonth为滑动的次数，每滑动一次就增加一月或减一月）
            Calendar cale1 = Calendar.getInstance();
            cale1.set(Calendar.YEAR, stepYear2);
            cale1.set(Calendar.MONTH, stepMonth2 - 1);
            cale1.set(Calendar.DATE, 3);
            MonthAttendsByUserList.clear();
            initCalender();
            doRequestHttp(new GetMonthAttendsByUserReq(cale1.getTimeInMillis()));
//                calendarAdapter = new CalendarAdapter(ResCheckActivity.this,
//                        getResources(), new Date(), jumpMonth, jumpYear,
//                        mYear, mMonth, mDay);
//                mGridView.setAdapter(calendarAdapter);
            // gvFlag++;
            addTextToTopTextView(topText);
        }

    }


    void initCalender() {
//        Calendar cal = Calendar.getInstance();
//         mYear = cal.get(Calendar.YEAR);//获取年份
//         mMonth=cal.get(Calendar.MONTH)+1;//获取月份
//         mDay=cal.get(Calendar.DATE);//获取日
        int stepYear = mYear + jumpYear;
        int stepMonth = mMonth + jumpMonth;
        if (stepMonth > 0) {
            //往下一个月滑动
            if (stepMonth % 12 == 0) {
                stepYear = mYear + stepMonth / 12 - 1;
                stepMonth = 12;
            } else {
                stepYear = mYear + stepMonth / 12;
                stepMonth = stepMonth % 12;
            }
        } else {
            //往上一个月滑动
            stepYear = mYear - 1 + stepMonth / 12;
            stepMonth = stepMonth % 12 + 12;
            if (stepMonth % 12 == 0) {

            }
        }

        currentYear = String.valueOf(stepYear);
        //得到当前的年份
        currentMonth = String.valueOf(stepMonth);  //得到本月 （jumpMonth为滑动的次数，每滑动一次就增加一月或减一月）
//		currentDay = String.valueOf(day_c);  //得到当前日期是哪天

        getCalendar(Integer.parseInt(currentYear), Integer.parseInt(currentMonth));
    }


    //得到某年的某月的天数且这月的第一天是星期几
    public void getCalendar(int year, int month) {
        isLeapyear = sc.isLeapYear(year);              //是否为闰年
        daysOfMonth = sc.getDaysOfMonth(isLeapyear, month);  //某月的总天数
        dayOfWeek = sc.getWeekdayOfMonth(year, month);      //某月第一天为星期几
        lastDaysOfMonth = sc.getDaysOfMonth(isLeapyear, month - 1);  //上一个月的总天数
        Log.e("DAY", isLeapyear + " ======  " + daysOfMonth + "  ============  " + dayOfWeek + "  =========   " + lastDaysOfMonth);
        MonthAttendsBeanList.clear();
        for (int i = 0; i < dayOfWeek; i++) {
            MonthAttendsBean bean = new MonthAttendsBean();
            bean.setDayType(MonthAttendsBean.DayType.LastMonth);
            int temp = lastDaysOfMonth - (dayOfWeek - i) + 1;
            bean.setDay(temp + "");
            MonthAttendsBeanList.add(bean);
        }

        GetMonthAttendsByUserEty[] array = new GetMonthAttendsByUserEty[daysOfMonth];

        for (int i = 0; i < array.length; i++) {
            MonthAttendsBean bean = new MonthAttendsBean();
            bean.setDay(i + 1 + "");
            if ((mDay == i + 1) && (mMonth == Integer.parseInt(currentMonth)))
                bean.setDayType(MonthAttendsBean.DayType.toDay);
            else
                bean.setDayType(MonthAttendsBean.DayType.currentMonth);

            for (int j = 0; j < MonthAttendsByUserList.size(); j++) {
                if (MonthAttendsByUserList.get(j).getAttendDay() != null) {
                    try {
                        Date date = sdf.parse(MonthAttendsByUserList.get(j).getAttendDay());
                        int day = date.getDate();
                        if (day == i + 1) {
                            bean.setUserEty(MonthAttendsByUserList.get(j));
                            break;
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
            MonthAttendsBeanList.add(bean);
        }

        int nextDay = 7 - MonthAttendsBeanList.size() % 7;
        for (int i = 0; i < nextDay; i++) {
            MonthAttendsBean bean = new MonthAttendsBean();
            bean.setDayType(MonthAttendsBean.DayType.LastMonth);
            bean.setDay(i + 1 + "");
            MonthAttendsBeanList.add(bean);
        }

        calendarAdapter.notifyDataSetChanged();

    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        return this.gestureDetector.onTouchEvent(event);
//    }

    // 添加头部的年份 闰哪月等信息
    public void addTextToTopTextView(TextView view) {
        StringBuffer textDate = new StringBuffer();
        textDate.append(currentYear).append("年")
                .append(currentMonth).append("月").append("\t");
        view.setText(textDate);
        view.setTextColor(Color.WHITE);
        view.setTypeface(Typeface.DEFAULT_BOLD);
    }

//    // 添加gridview
//    private void addGridView() {
//
//        mGridView = (GridView) findViewById(R.id.gridview);
//        mGridView.setOnTouchListener(new View.OnTouchListener() {
//
//            @Override
//            public boolean onTouch(View v, MotionEvent event) {
//                v.performClick();
//                // 将Gridview中的触摸事件回传给gestureDetector
//                return ResCheckActivity.this.gestureDetector
//                        .onTouchEvent(event);
//            }
//        });
//
////        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
////            // gridView中的每一个item的点击事件
////            @Override
////            public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
////                // 点击任何一个item，得到这个item的日期(排除点击的是周日到周六(点击不响应))
////                int startPosition = calendarAdapter.getStartPositon();
////                int endPosition = calendarAdapter.getEndPosition();
////                if (startPosition <= position + 7 && position <= endPosition - 7) {
////                    String scheduleDay = calendarAdapter.getDateByClickItem(position).split("\\.")[0]; // 这一天的阳历
////                    String scheduleMonth = calendarAdapter.getShowMonth();
////                    Toast.makeText(ResCheckActivity.this, calendarAdapter.getShowYear() + "-" + scheduleMonth + "-" + scheduleDay, Toast.LENGTH_SHORT).show();
////                }
////            }
////        });
//    }

//    //滑动手势的监听
//    private class MyGestureListener extends
//            GestureDetector.SimpleOnGestureListener {
//        // 用户（轻触触摸屏后）松开，由一个1个MotionEvent ACTION_UP触发
//        @Override
//        public boolean onSingleTapUp(MotionEvent e) {
//            return super.onSingleTapUp(e);
//        }
//
//        // 用户长按触摸屏，由多个MotionEvent ACTION_DOWN触发
//        @Override
//        public void onLongPress(MotionEvent e) {
//            super.onLongPress(e);
//        }
//
//        // 用户按下触摸屏，并拖动，由1个MotionEvent ACTION_DOWN,
//        // 多个ACTION_MOVE触发
//        @Override
//        public boolean onScroll(MotionEvent e1, MotionEvent e2,
//                                float distanceX, float distanceY) {
//            return super.onScroll(e1, e2, distanceX, distanceY);
//        }
//
//        // 用户按下触摸屏、快速移动后松开，由1个MotionEvent ACTION_DOWN,
//        // 多个ACTION_MOVE, 1个ACTION_UP触发
//        @Override
//        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
//                               float velocityY) {
//            // int gvFlag = 0; //每次添加gridview到viewflipper中时给的标记
//            if (e1.getX() - e2.getX() > 120) {
//                // 向左滑动
//                nextMonth.performClick();
//                return true;
//            } else if (e1.getX() - e2.getX() < -120) {
//                // 向右滑动
//                preMonth.performClick();
//                return true;
//            }
//            return false;
//        }
//
//        // 用户轻触触摸屏，尚未松开或拖动，由一个1个MotionEvent ACTION_DOWN触发
//        // 注意和onDown()的区别，强调的是没有松开或者拖动的状态
//        public void onShowPress(MotionEvent e) {
//            super.onShowPress(e);
//        }
//
//        // 用户轻触触摸屏，由1个MotionEvent ACTION_DOWN触发
//        @Override
//        public boolean onDown(MotionEvent e) {
//            return super.onDown(e);
//        }
//
//        // 双击的第二下Touch down时触发
//        @Override
//        public boolean onDoubleTap(MotionEvent e) {
//            return super.onDoubleTap(e);
//        }
//
//        // 双击的第二下Touch down和up都会触发，可用e.getAction()区分
//        @Override
//        public boolean onDoubleTapEvent(MotionEvent e) {
//            return super.onDoubleTapEvent(e);
//        }
//
//        // 点击一下稍微慢点的(不滑动)Touch Up:
//        // onDown->onShowPress->onSingleTapUp->onSingleTapConfirmed
//        @Override
//        public boolean onSingleTapConfirmed(MotionEvent e) {
//            return super.onSingleTapConfirmed(e);
//        }
//
//    }

}
